package com.ewhale.feitengguest.ui.user;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioGroup;

import com.ewhale.feitengguest.R;
import com.ewhale.feitengguest.dto.ArticleDetailDto;
import com.ewhale.feitengguest.dto.VersionDto;
import com.ewhale.feitengguest.presenter.user.MainPresenter;
import com.ewhale.feitengguest.receiver.TagAliasOperatorHelper;
import com.ewhale.feitengguest.ui.WebViewActivity;
import com.ewhale.feitengguest.ui.auth.LoginActivity;
import com.ewhale.feitengguest.ui.shop.ShopMainActivity;
import com.ewhale.feitengguest.ui.user.message.MessageFragment;
import com.ewhale.feitengguest.ui.user.message.chat.AuthHelper;
import com.ewhale.feitengguest.ui.user.mine.MineFragment;
import com.ewhale.feitengguest.ui.user.task.TaskFragment;
import com.ewhale.feitengguest.utils.Contants;
import com.ewhale.feitengguest.utils.UserInfoUtils;
import com.ewhale.feitengguest.view.user.MainView;
import com.ewhale.feitengguest.widget.PrivacyDialog;
import com.ewhale.feitengguest.widget.VersionDialog;
import com.orhanobut.hawk.Hawk;
import com.simga.library.activity.MBaseActivity;
import com.simga.library.utils.AppManager;
import com.simga.library.utils.HawkKey;
import com.simga.library.utils.SystemUtil;

import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import butterknife.BindView;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.wechat.Wechat;

import static com.ewhale.feitengguest.receiver.TagAliasOperatorHelper.ACTION_DELETE;
import static com.ewhale.feitengguest.receiver.TagAliasOperatorHelper.ACTION_SET;
import static com.ewhale.feitengguest.receiver.TagAliasOperatorHelper.sequence;

/**
 * Author：SimGa
 * CoryRight：2018/11/15
 * PackageName：com.ewhale.imissyou.userside.ui.business
 */
public class MainActivity extends MBaseActivity<MainPresenter> implements MainView {

    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    private PrivacyDialog mDailog;

    @Override
    protected int getViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        registerReceiver();
        replaceFragment(TaskFragment.class.getName());
        presenter.checkVersion();
        mDailog = new PrivacyDialog(mContext);
        boolean isAgree = Hawk.get(HawkKey.AGREE_XIEYI, false);
        if (!isAgree) {
            mDailog.show();
        }

    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    @Override
    protected void initListener() {
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            View checkView = findViewById(checkedId);
            if (!checkView.isPressed()) {
                return;
            }
            switch (checkedId) {
                case R.id.rb_task:
                    replaceFragment(TaskFragment.class.getName());
                    break;
                case R.id.rb_message:
                    if (!Hawk.get(HawkKey.IS_USER_LOGIN, false)) {
                        radioGroup.check(R.id.rb_task);
                        LoginActivity.open(mContext);
                        return;
                    }
                    replaceFragment(MessageFragment.class.getName());
                    break;
                case R.id.rb_mine:
                    if (!Hawk.get(HawkKey.IS_USER_LOGIN, false)) {
                        radioGroup.check(R.id.rb_task);
                        LoginActivity.open(mContext);
                        return;
                    }
                    replaceFragment(MineFragment.class.getName());
                    break;
            }
        });
        mDailog.setListenter(new PrivacyDialog.onClickListenter() {
            @Override
            public void onClickYonghu() {
                presenter.loadArticleDetails(1);
            }

            @Override
            public void onClickyinsi() {
                presenter.loadArticleDetails(11);
            }

            @Override
            public void onClickAgree() {
                Hawk.put(HawkKey.AGREE_XIEYI, true);
            }

            @Override
            public void onClickNoAgree() {
                AlertDialog.Builder alertdialogbuilder = new AlertDialog.Builder(mContext);
                alertdialogbuilder.setMessage("您不同意此协议，将无法使用App，请同意。");
                alertdialogbuilder.setPositiveButton("确定", null);
                alertdialogbuilder.setNeutralButton("不同意", (dialog, which) -> {
                    mDailog.dismiss();
                    finishSimple();
                });
                final AlertDialog alertdialog1 = alertdialogbuilder.create();
                alertdialog1.show();
            }
        });
    }

    @Override
    public void showDetail(ArticleDetailDto result, int type) {
        if (type == 1) {
            WebViewActivity.open(mContext, "用户协议", result.content);
        } else if (type == 11) {
            WebViewActivity.open(mContext, "隐私保护协议", result.content);
        }
    }

    protected void replaceFragment(String tag) {
        Fragment tempFragment = getSupportFragmentManager().findFragmentByTag(tag);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (tempFragment == null) {
            try {
                tempFragment = (Fragment) Class.forName(tag).newInstance();
                transaction.add(R.id.fragmentContainer, tempFragment, tag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null) {
            for (int i = 0; i < fragments.size(); i++) {
                Fragment fragment = fragments.get(i);
                if (fragment.getTag().equals(tag)) {
                    transaction.show(fragment);
                } else
                    transaction.hide(fragment);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    private long lastTimePressed = 0;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - lastTimePressed < 1000) {
            finishSimple();
        } else {
            lastTimePressed = System.currentTimeMillis();
            showToast("再按一次退出程序");
        }
    }

    public static void open(MBaseActivity mContext) {
        mContext.startActivity(null, MainActivity.class);
    }


    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("USER_LOGIN_ANOTHER_DEVICE");
        filter.addAction(HawkKey.USER_LOGIN_OUT);
        filter.addAction("JUMP_MESSAGE");
        filter.addAction("JUMP_INVITE_LIST");
        registerReceiver(myReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(HawkKey.USER_LOGIN_OUT) || intent.getAction().equals("USER_LOGIN_ANOTHER_DEVICE")) {
                UserInfoUtils.INSTANCE.deleteUserInfo(1);
                AppManager.get().finishActivitiesWithoutTarget(MainActivity.class);
                //未登录或者登录失效，跳转至首页
                ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                String activityName = am.getRunningTasks(1).get(0).topActivity.getClassName();
                try {
                    Class classObject = Class.forName(activityName);
                    if (classObject.getSimpleName().equals("MainActivity")) {
                        radioGroup.check(R.id.rb_task);
                        replaceFragment(TaskFragment.class.getName());
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                if (Hawk.get(HawkKey.IS_SHOP_LOGIN, false)) {
                    Hawk.put(HawkKey.NOW_APP_STATUS, Contants.SHOP_STATUS);
                    ShopMainActivity.open(mContext);
                    finish();
                } else {
                    LoginActivity.open(mContext);
                }
            } else if (intent.getAction().equals("JUMP_MESSAGE") || intent.getAction().equals("JUMP_INVITE_LIST")) {
                radioGroup.check(R.id.rb_message);
                replaceFragment(MessageFragment.class.getName());
            }
        }
    };


    @Override
    public void showProLoading() {
        showLoading();
    }

    @Override
    public void dimissProLoading() {
        dismissLoading();
    }

    @Override
    public void showErrorMessage(int postCode, String code, String message) {
        showErrorMsg(code, message);
    }


    @Override
    public void showVersion(VersionDto result) {
        if (Integer.parseInt(result.getVersion().replace(".", "")) > Integer.parseInt(SystemUtil.getVersionName(mContext).replace(".", ""))) {
            VersionDialog mDialog = new VersionDialog(mContext, result.getContent(), result.getIsForce());
            mDialog.setListenter(() -> {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(result.getUrl());
                intent.setData(content_url);
                startActivity(intent);
            });
            mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (result.getIsForce() == 1) {//是否强更新   是
                        //注销第三方登录
                        if (Hawk.get(HawkKey.LOGIN_THIRD_TYPE, "").equals(Contants.weChat)) {
                            JShareInterface.removeAuthorize(Wechat.Name, null);
                        } else if (Hawk.get(HawkKey.LOGIN_THIRD_TYPE, "").equals(Contants.qq)) {
                            JShareInterface.removeAuthorize(QQ.Name, null);
                        }
                        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
                        tagAliasBean.action = ACTION_DELETE;
                        sequence++;
                        tagAliasBean.alias = "";
                        tagAliasBean.isAliasAction = true;
                        TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean);
                        //清除数据
                        Hawk.delete(HawkKey.USER_AUTHENTICATION);
                        Hawk.delete(HawkKey.LOGIN_THIRD_TYPE);
                        Hawk.delete(HawkKey.IS_USER_LOGIN);
                        Hawk.delete(HawkKey.USER_LOGIN_INFO);
                        Hawk.delete(HawkKey.USER_PHONE);
//                        Hawk.delete(HawkKey.IS_SETT_ALIAS);
                        //退出整个APP
                        System.exit(0);
                    }
                }
            });
            mDialog.show();
        }
    }
}